package com.sczmgk.hotline.base;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.sczmgk.hotline.MyApp;
import com.sczmgk.hotline.R;
import com.sczmgk.hotline.activity.ChatActivity;
import com.sczmgk.hotline.callback.ActivityCallback;
import com.sczmgk.hotline.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline.constant.Constant;
import com.sczmgk.hotline.db.impl.UserDaoImpl;
import com.sczmgk.hotline.dialog.DialogFactory;
import com.sczmgk.hotline.dialog.MessageDialog;
import com.sczmgk.hotline.entity.HxAccount;
import com.sczmgk.hotline.entity.User;
import com.sczmgk.hotline.httpUtils.MyHttp;
import com.sczmgk.hotline.jpush.ExampleUtil;
import com.sczmgk.hotline.jpush.JShareUtils;
import com.sczmgk.hotline.jpush.MyShareParms;
import com.sczmgk.hotline.popup.PupDialog;
import com.sczmgk.hotline.utils.CacheUtils;
import com.sczmgk.hotline.utils.MyLog;
import com.sczmgk.hotline.utils.MyToast;
import com.sczmgk.hotline.utils.Tools;
import com.sczmgk.hotline.view.MyHeadView;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.qqmodel.QZone;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.weibo.SinaWeibo;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static com.sczmgk.hotline.MainActivity.CHAT_REQUEST_CODE;


public abstract class BaseActivity extends AppCompatActivity implements ActivityCallback {

    /**
     * 错误信息发送的msg
     */
    public static final int ON_ERROR_CODE_ERROR_MSG = 232;

    /**
     * 访问成功后发送的msg
     */
    public static final int ON_LOAD_SUCCESS = 132;

    protected static final int REGIST_HX_FAIL_MSG = 1500;

    private static final int MSG_SET_ALIAS = 1001;

    private static final int MSG_SET_TAGS = 1002;


    protected FrameLayout videoView;
    protected String TAG = this.getClass().getSimpleName();
    private Dialog loadingDialog;

    /**
     * 自定义title
     */
    private MyHeadView mHeadView;
    private MessageDialog successDialog;
    private MessageDialog errorDialog;

    protected AtomicBoolean isSingleLoginHx;

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    /**
     * 界面容器
     */
    protected FrameLayout mLinearLayoutContent;

    private LayoutInflater mLayoutInflater;
    /**
     * base布局
     */
    public View baseLayout;
    /**
     * 底部弹出框的 引用
     */
    public PupDialog menuWindow = null;
    public PopupWindow sharePup = null;
    protected Handler mHandler = null;

    //    @SuppressLint("HandlerLeak")
    private void initHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ON_ERROR_CODE_ERROR_MSG:
                        String errorMsg = (String) msg.obj;
                        if (errorDialog == null) {
                            showDialog(errorMsg);
                        } else if (!errorDialog.isShowing()) {
                            showDialog(errorMsg);
                        }
                        break;
                    case ON_LOAD_SUCCESS:
                        int res = (int) msg.obj;
                        if (successDialog == null) {
                            showSuccDialog(res);
                        } else if (!successDialog.isShowing()) {
                            showSuccDialog(res);
                        }
                        break;
                }
                BaseActivity.this.handleMessage(msg);
            }
        };
    }

    private void showSuccDialog(int res) {
        successDialog = DialogFactory.warningDialog(BaseActivity.this, getResources().getString(res), R.string.sure, new OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void showDialog(String errorMsg) {
        errorDialog = DialogFactory.warningDialog(BaseActivity.this, errorMsg, R.string.back, new OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
    }

    public abstract void handleMessage(Message msg);

    /**
     * @param pupid    弹出框的 id
     * @param pupEvent 弹出框 按钮的监听事件接口
     */
    @Override
    public void showPup(String pupid, PupDialog.PupEvent pupEvent) {
        dismissPup();
        menuWindow = new PupDialog(this, pupid, pupEvent);

        menuWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 显示窗口
        menuWindow.showAtLocation(baseLayout, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void dismissPup() {
        if (null != menuWindow && menuWindow.isShowing()) {
            menuWindow.dismiss();
        }
    }

    protected void showClientDialog(int des) {
        DialogFactory.warningDialog(BaseActivity.this, des, R.string.sure, new OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isSingleLoginHx = new AtomicBoolean(true);

        super.setContentView(R.layout.layout_include_title);
        initHandler();
        mLayoutInflater = LayoutInflater.from(this);

        mHeadView = (MyHeadView) findViewById(R.id.headview);
        videoView = (FrameLayout) findViewById(R.id.fl_video_view);
        mHeadView.setLeftBtnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onLeftButtonClick();
            }
        });
        mHeadView.setRightBtnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onRightButtonClick();
            }
        });

        mHeadView.setNextRightBtnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onNextRightButtonClick();
            }
        });

        mLinearLayoutContent = (FrameLayout) findViewById(R.id.main_home_container);
        baseLayout = findViewById(R.id.layout_base);
        mHeadView.setLeftCloseBtnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }


    protected void onRightButtonClick() {

    }


    private void onNextRightButtonClick() {

    }


    protected void onLeftButtonClick() {
        finish();
    }

    public void goneHeadView() {
        mHeadView.setVisibility(View.GONE);
    }

    @Override
    public void visibleHeadView() {
        mHeadView.setVisibility(View.VISIBLE);
    }

    public int getLeftBtnBGResource() {
        return mHeadView.getLeftBtnBGResource();
    }

    @Override
    public void setLeftBtnEnabled(boolean enabled) {
        mHeadView.getBtnLeft().setEnabled(enabled);
    }

    @Override
    public void setLeftBtnVisibility(int visible) {
        mHeadView.setLeftBtnVisibility(visible);
    }

    @Override
    public void setLeftBtnBackground(int resource) {
        mHeadView.setLeftBtnBackground(resource, -1);
    }

    @Override
    public void setLeftBtnBackground(int resource, int text) {
        mHeadView.setLeftBtnBackground(resource, text);
    }

    @Override
    public void setLeftBtnBackground(int resource, int text, int textColorResource) {
        mHeadView.setLeftBtnBackground(resource, text, textColorResource);
    }

    @Override
    public void setLeftBtnTextColor(int textColorResource) {
        mHeadView.setLeftBtnTextColor(textColorResource);
    }

    @Override
    public void setLeftBtnText(String text) {
        mHeadView.setLeftBtnText(text);
    }

    @Override
    public void setLeftBtnClickListener(OnClickListener listener) {
        mHeadView.setLeftBtnClickListener(listener);
    }

    @Override
    public void setRightBtnEnabled(boolean enabled) {
        mHeadView.getBtnRight().setEnabled(enabled);
    }

    @Override
    public void setRightBtnVisibility(int visible) {
        mHeadView.setRightBtnVisibility(visible);
    }

    @Override
    public void setRightBtnBackground(int resource) {
        mHeadView.setRightBtnBackground(resource, -1);
    }

    @Override
    public void setRightBtnDescription(String desc) {
        mHeadView.setRightBtnDesc(desc);
    }

    @Override
    public void setRightBtnBackground(int resource, int text) {
        mHeadView.setRightBtnBackground(resource, text);
    }

    public void setRightBtnBackground(int resource, String text) {
        mHeadView.setRightBtnBackground(resource, text);
    }

    @Override
    public void setRightBtnBackground(int resource, int text, int textColorResource) {
        mHeadView.setRightBtnBackground(resource, text, textColorResource);
    }

    @Override
    public void setRightBtnTextColor(int textColorResource) {
        mHeadView.setRightBtnTextColor(textColorResource);
    }

    @Override
    public void setRightBtnText(int resid) {
        mHeadView.setRightBtnText(resid);
    }

    @Override
    public void setRightBtnClickListener(OnClickListener listener) {
        mHeadView.setRightBtnClickListener(listener);
    }

    public int getRightBtnBGResource() {
        return mHeadView.getRightBtnBGResource();
    }

    @Override
    public void setTitleIcon(int resource) {
        mHeadView.setTitleIcon(resource);
    }

    @Override
    public void setTitle(int resource) {
        if (resource > 0) {
            mHeadView.setTitle(resource);
        }
    }

    @Override
    public void setTitle(String title) {
        if (!Tools.isEmpty(title)) {
            mHeadView.setTitle(title);
        }
    }

    @Override
    public void setTitleColor(int color) {
        mHeadView.setTitleColor(color);
    }

    @Override
    public void setNextRightBtnEnabled(boolean enabled) {
        mHeadView.getBtnRight().setEnabled(enabled);
    }

    @Override
    public void setNextRightBtnVisibility(int visible) {
        mHeadView.setNextRightBtnVisibility(visible);
    }

    @Override
    public void setNextRightBtnBackground(int resource) {
        mHeadView.setNextRightBtnBackground(resource, -1);
    }

    @Override
    public void setNextRightBtnDescription(String desc) {
        mHeadView.setNextRightBtnDesc(desc);
    }

    @Override
    public void setNextRightBtnBackground(int resource, int text) {
        mHeadView.setNextRightBtnBackground(resource, text);
    }

    public void setNextRightBtnBackground(int resource, String text) {
        mHeadView.setRightBtnBackground(resource, text);
    }

    @Override
    public void setNextRightBtnBackground(int resource, int text, int textColorResource) {
        mHeadView.setNextRightBtnBackground(resource, text, textColorResource);
    }

    @Override
    public void setNextRightBtnTextColor(int textColorResource) {
        mHeadView.setNextRightBtnTextColor(textColorResource);
    }

    @Override
    public void setNextRightBtnText(int resid) {
        mHeadView.setNextRightBtnText(resid);
    }

    @Override
    public void setNextRightBtnClickListener(OnClickListener listener) {
        mHeadView.setNextRightBtnClickListener(listener);
    }

    //TODO 分享按钮的点击事件
    public void setShareBtnClickListener(OnClickListener listener) {
        mHeadView.setShareBtnClickListener(listener);
    }

    //TODO 分享按钮的显示
    public void setShareBtnVisiable(int visible) {
        mHeadView.setShareBtnVisibility(visible);
    }

    //TODO 分享按钮的北京
    public void setShareBtnBGResource(int res) {
        mHeadView.setShareBtnBackground(res);
    }

    public int getNextRightBtnBGResource() {
        return mHeadView.getNextRightBtnBGResource();
    }

    public void setTitleIconText(int res) {
        mHeadView.setTitleIconText(res);
    }

    public void setTitleIconText(String res) {
        mHeadView.setTitleIconText(res);
    }

    public void setTitleIconClick(OnClickListener listener) {
        mHeadView.setTitleIconClick(listener);
    }

    public void setTitleIconVisiable(int visiable) {
        mHeadView.setTitleIconVisiable(visiable);
    }


    public void setRightTitleText(String text) {
        mHeadView.setTitleText(text);
    }

    public void setRightTitleText(int res) {
        mHeadView.setTitleText(res);
    }

    public void setRightTitleClick(OnClickListener listener) {
        mHeadView.setTitleClick(listener);
    }

    public void setRightTitleClickListener(OnClickListener listener) {
        mHeadView.setRightTitleClickListener(listener);
    }

    public void setRightTitleVisiable(int visiable) {
        mHeadView.setTitleVisiable(visiable);
    }


    @Override
    public void setHeadBackgroudColor(int color) {
        mHeadView.setHeadBackground(color);
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = mLayoutInflater.inflate(layoutResID, null);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        mLinearLayoutContent.removeAllViews();
        mLinearLayoutContent.addView(view, lp);
    }

    @Override
    public void setContentView(View view, LayoutParams params) {
        mLinearLayoutContent.removeAllViews();
        mLinearLayoutContent.addView(view, params);
    }

    @Override
    public void setContentView(View view) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        mLinearLayoutContent.removeAllViews();
        mLinearLayoutContent.addView(view, lp);
    }

    protected int getContendId() {
        return R.id.main_home_container;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    protected void showFragment(int resId, Fragment fragment) {
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getIsNeedLogin()) {
            boolean isLogin = CacheUtils.getLoginStatus(BaseActivity.this);
            if (!isLogin) {
                finish();
            }
        }
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        dismissLoadingDiaLog();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public MyHeadView getHeadView() {
        return mHeadView;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent arg2) {
        super.onActivityResult(requestCode, resultCode, arg2);
        switch (requestCode) {
            case CHAT_REQUEST_CODE:
                // TODO 调用服务的开启定时器方法
                if (arg2 != null) {
//                    boolean isAndroid = arg2.getBooleanExtra("isAndroid", true);
//                    msgTimerService.startTimer(isAndroid);
                }
                break;
        }
    }

    public void cancelTask(List<AsyncTask<?, ?, ?>> tasks) {
        if (tasks == null || tasks.size() == 0) {
            return;
        }

        for (AsyncTask<?, ?, ?> task : tasks) {
            if (task != null && AsyncTask.Status.RUNNING == task.getStatus()) {
                task.cancel(true);
            }
        }
    }

    @Override
    public void setHeadViewVisibility(int visible) {
        mHeadView.setVisibility(visible);
    }

    public void setLeftCloseBtnVisibility(int visible) {
        mHeadView.setLeftCloseBtnVisibility(visible);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;

        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void setCustomVideoView(View view) {
        videoView.setVisibility(View.VISIBLE);
        videoView.addView(view);
    }

    public void hidecustomVideoView() {
        videoView.removeAllViews();
        videoView.setVisibility(View.GONE);
    }

    protected void showLoadingDiaLog() {
        DialogFactory.dismissLoadingDialog(BaseActivity.this, loadingDialog);
        if (loadingDialog == null) {
            loadingDialog = DialogFactory.getLoadingDialog(BaseActivity.this, R.string.dialog_loading);
        }
        DialogFactory.showDialog(BaseActivity.this, loadingDialog);
    }

    protected void dismissLoadingDiaLog() {
        DialogFactory.dismissLoadingDialog(BaseActivity.this, loadingDialog);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    public void showErrorMsg(String msg) {
        Message message = Message.obtain();
        message.what = ON_ERROR_CODE_ERROR_MSG;
        message.obj = msg;
        mHandler.sendMessage(message);
    }

    public void showSuccessDialog(int res) {
        Message message = Message.obtain();
        message.what = ON_LOAD_SUCCESS;
        message.obj = res;
        mHandler.sendMessage(message);
    }

    protected void login(final boolean isAndroid) {
        if (isSingleLoginHx.get()) {
            isSingleLoginHx.set(false);
            MyLog.i(TAG, "环信注册---------------------------" + isSingleLoginHx.get());
            //区分游客与用户
            if (CacheUtils.getLoginStatus(BaseActivity.this)) {
                User loginUser = UserDaoImpl.getLoginUser(BaseActivity.this);
                //取到用户
                if (loginUser != null && CacheUtils.getLoginStatus(BaseActivity.this)) {
                    if (!Tools.isEmpty(loginUser.hxaccount)) {
                        //取得环信帐号,登录环信
                        loginHx(loginUser.hxaccount, loginUser.hxpwd,isAndroid);
                    } else {
                        //注册环信
                        registerHx(isAndroid);
                    }
                } else {
                    registerHx(isAndroid);
                }
            } else {
                registerHx(isAndroid);
            }
        }
    }
    protected void loginTest(boolean isAndroid) {
        loginHx("keke01", "123456",isAndroid);
    }

    protected void loginHx(final String account, final String pwd,final boolean isAndroid) {
        if (com.sczmgk.frame.http.Tools.isEmpty(account) || com.sczmgk.frame.http.Tools.isEmpty(pwd)) {
            isSingleLoginHx.set(true);
            MyLog.e(TAG, "没有取到环信帐号，密码");
            return;
        }
        EMClient.getInstance().login(account, pwd, new EMCallBack() {
            @Override
            public void onSuccess() {
                MyLog.i(TAG, "登录成功");
                isSingleLoginHx.set(true);
                MyLog.i(TAG, "环信登录成功---------------------------" + isSingleLoginHx.get());
                loginSuccess(isAndroid);
            }

            @Override
            public void onError(int i, String s) {
                MyLog.i(TAG, "环信登录失败---------------------------" + isSingleLoginHx.get());
                isSingleLoginHx.set(true);
                if (i == 200) {
                    MyLog.i(TAG, "登录成功");
                    loginSuccess(isAndroid);
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MessageDialog dialog = DialogFactory.chooseDialog(BaseActivity.this, "登录失败,请重试,如选择取消则不会发起人工在线咨询", "确定", "取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    isSingleLoginHx.set(true);
                                    loginHx(account, pwd,isAndroid);
                                }
                            }, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    isSingleLoginHx.set(true);
                                }
                            });
                            com.hyphenate.easeui.utils.MyLog.e(TAG, "登录失败");
                            dialog.setTitle("提示");
                            dialog.show();
                        }
                    });

                }

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    protected void loginSuccess(final boolean isAndroid) {
        Intent intent = new Intent(BaseActivity.this, ChatActivity.class);
        intent.putExtra(EaseConstant.EXTRA_USER_ID, MyApp.HX_SERVICE);
        intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        intent.putExtra("isAndroid",isAndroid);
        startActivityForResult(intent, CHAT_REQUEST_CODE);
    }

    protected void registerHx(final boolean isAndroid) {
        Map<String, Object> datamap = new HashMap<>();
//        datamap.put("imei",MyApp.imei);
        MyHttp.request(BaseActivity.this, Constant.BASE_URL + Constant.GET_HX_ACCOUNT, datamap, MyHttp.POST, false, null, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {
                isSingleLoginHx.set(true);
            }

            @Override
            public void onVerifySuccess(String dataRaw) {
                Gson gson = new Gson();
                HxAccount hxAccount = gson.fromJson(dataRaw, HxAccount.class);
                if (hxAccount != null && !com.sczmgk.frame.http.Tools.isEmpty(hxAccount.username)) {
                    loginHx(hxAccount.username, hxAccount.password,isAndroid);
                } else {
                    isSingleLoginHx.set(true);
                    MyLog.e(TAG, "注册环信失败");
                    Message msg = Message.obtain();
                    msg.what = REGIST_HX_FAIL_MSG ;
                    msg.obj = "注册环信失败";
                    mHandler.sendMessage(msg);
                }
            }

            @Override
            public void onServerUnKnownError() {
                isSingleLoginHx.set(true);
                Message msg = Message.obtain();
                msg.what = REGIST_HX_FAIL_MSG ;
                msg.obj = "注册环信失败";
                mHandler.sendMessage(msg);
            }

            @Override
            public void onErrorCodeError(String msg) {
                isSingleLoginHx.set(true);
                Message message = Message.obtain();
                message.what = REGIST_HX_FAIL_MSG ;
                message.obj = msg;
                mHandler.sendMessage(message);
            }
        });
    }

    private final Handler mJpushHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    MyLog.d(TAG, "Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    //测试注销推送
                    break;

                case MSG_SET_TAGS:
                    MyLog.d(TAG, "Set tags in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
                    break;

                case REGIST_HX_FAIL_MSG :
                    String msgDes = (String) msg.obj;
                    MyToast.show(BaseActivity.this,msgDes);
                    break;
                default:
                    MyLog.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };


    /**
     * 别名回调接口
     */

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    MyLog.d(TAG, "onResult   jpush");
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    MyLog.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mJpushHandler.sendMessageDelayed(mJpushHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        MyLog.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    MyLog.e(TAG, logs);
            }

//            ExampleUtil.showToast(logs, getApplicationContext());
        }

    };
    /**
     * 标签回调接口
     */
    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    MyLog.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    MyLog.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mJpushHandler.sendMessageDelayed(mJpushHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    } else {
                        MyLog.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    MyLog.e(TAG, logs);
            }

            ExampleUtil.showToast(logs, getApplicationContext());
        }

    };

    /**
     * 设置tag(区域码)
     *
     * @param tag
     */
    private void setJpushTag(String tag) {

        // 检查 tag 的有效性
        if (TextUtils.isEmpty(tag)) {
//			Toast.makeText(PushSetActivity.this,R.string.error_tag_empty, Toast.LENGTH_SHORT).show();
            return;
        }

        // ","隔开的多个 转换成 Set
        String[] sArray = tag.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!ExampleUtil.isValidTagAndAlias(sTagItme)) {
//				Toast.makeText(PushSetActivity.this,R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show();
                return;
            }
            tagSet.add(sTagItme);
        }

        //调用JPush API设置Tag
        mJpushHandler.sendMessage(mJpushHandler.obtainMessage(MSG_SET_TAGS, tagSet));

    }

    /**
     * 设置别名(imei)
     *
     * @param alias
     */
    protected void setAlias(String alias) {
        MyLog.d(TAG, "set alias : " + alias);
//		EditText aliasEdit = (EditText) findViewById(R.id.et_alias);
//		String alias = aliasEdit.getText().toString().trim();
        if (TextUtils.isEmpty(alias)) {
//			Toast.makeText(PushSetActivity.this,R.string.error_alias_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!ExampleUtil.isValidTagAndAlias(alias)) {
//			MyToast.show(LoginActivity.this,"推送别名不符合规则 :"+alias);
            return;
        }
//        MyToast.show(LoginActivity.this,"推送别名是 :"+alias);
        //调用JPush API设置Alias
        mJpushHandler.sendMessage(mJpushHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private JShareUtils.ShareCallback shareCallback;
    private MyShareParms shareParams;

    public void showSharePup(final JShareUtils.ShareCallback shareCallback, MyShareParms shareParams) {

        this.shareParams = shareParams;
        if (null != sharePup && sharePup.isShowing()) {
            sharePup.dismiss();
        }
        if (shareParams == null) {
            return;
        }
        this.shareCallback = shareCallback;

        if (shareCallback == null) {
            return;
        }

        initSharePop();
        sharePup.setAnimationStyle(R.style.mypopwindow_anim_style);

        sharePup.showAtLocation(baseLayout, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void initSharePop() {
        if (sharePup != null) {
            return;
        }
        sharePup = new PopupWindow();

        LayoutInflater lf = LayoutInflater.from(this);
        LinearLayout windowView = (LinearLayout) lf.inflate(R.layout.share_layout, null);

        TextView cancel = (TextView) windowView.findViewById(R.id.tv_cancel_share);
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sharePup.dismiss();
            }
        });
        GridView gv = (GridView) windowView.findViewById(R.id.gv_share);
        gv.setAdapter(new ShareAdapter());
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(final AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 0:
                        MyLog.d(TAG, "share to qq");
                        sharePup.dismiss();
                        boolean qq = JShareInterface.isClientValid(QQ.Name);
                        if (qq) {
                            share(QQ.Name);
                        } else {
                            showClientDialog(R.string.is_qq_client_install);
                        }
                        break;
                    case 1:
                        MyLog.d(TAG, "share to Qzone");
                        sharePup.dismiss();
                        boolean qzone = JShareInterface.isClientValid(QZone.Name);
                        if (qzone) {
                            share(QZone.Name);
                        } else {
                            showClientDialog(R.string.is_qq_client_install);
                        }
                        break;
                    case 2:
                        MyLog.d(TAG, "share to sina");

                        sharePup.dismiss();
                        boolean sina = JShareInterface.isClientValid(SinaWeibo.Name);
                        if (sina) {
                            share(SinaWeibo.Name);
                        } else {
                            showClientDialog(R.string.is_sina_client_install);
                        }
                        break;
                    case 3:
                        MyLog.d(TAG, "share to weichat");
                        sharePup.dismiss();
                        boolean weChat = JShareInterface.isClientValid(Wechat.Name);
                        if (weChat) {
                            share(Wechat.Name);
                        } else {
                            showClientDialog(R.string.is_wechat_client_install);
                        }
                        break;
                }
            }
        });

        // 设置SelectPicPopupWindow的View
        sharePup.setContentView(windowView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        sharePup.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        sharePup.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        sharePup.setFocusable(true);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        // this.setAnimationStyle(R.style.AnimBottom);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x55000000);
        // 设置SelectPicPopupWindow弹出窗体的背景
        sharePup.setBackgroundDrawable(dw);
        // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框

    }

    public void share(String platform) {
        JShareUtils.getInstance().shareByWebPage(platform, shareParams, new JShareUtils.ShareCallback() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

                if (shareCallback != null) {
                    shareCallback.onComplete(platform, i, hashMap);
                }
            }

            @Override
            public void onError(Platform platform, int i, int i1, Throwable throwable) {
                if (shareCallback != null) {
                    shareCallback.onError(platform, i, i1, throwable);
                }
            }

            @Override
            public void onCancel(Platform platform, int i) {
                if (shareCallback != null) {
                    shareCallback.onCancel(platform, i);
                }
            }
        });
    }

    public class ShareAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return 4;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(BaseActivity.this, R.layout.share_item, null);
            ImageView icon = (ImageView) view.findViewById(R.id.iv_share_icon);
            TextView tv = (TextView) view.findViewById(R.id.tv_share_platform);
            switch (position) {
                case 0:
                    icon.setBackgroundResource(R.drawable.jiguang_socialize_qq);
                    tv.setText("QQ");
                    break;
                case 1:
                    icon.setBackgroundResource(R.drawable.jiguang_socialize_qzone);
                    tv.setText("QQ空间");
                    break;
                case 2:
                    icon.setBackgroundResource(R.drawable.jiguang_socialize_sina);
                    tv.setText("微博");
                    break;
                case 3:
                    icon.setBackgroundResource(R.drawable.jiguang_socialize_wechat);
                    tv.setText("微信");
                    break;
            }
            return view;
        }
    }



}
